package com.powernode.domain;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.*;

/**
 * 内容:
 * 作者: cy
 */

/**
 * 系统用户
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "sys_user")
public class SysLoginUser implements Serializable, UserDetails {
    @TableId(value = "user_id", type = IdType.AUTO)
    private Long userId;

    /**
     * 用户名
     */
    @TableField(value = "username")
    private String username;

    /**
     * 密码
     */
    @TableField(value = "password")
    private String password;

    /**
     * 状态  0：禁用   1：正常
     */
    @TableField(value = "status")
    private Integer status;

    /**
     * 用户所在的商城Id
     */
    @TableField(value = "shop_id")
    private Long shopId;

    @TableField(exist = false)
    private List<String> auths;

    /**
     * 处理权限
     *
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (CollectionUtils.isEmpty(auths)) {
            return Collections.emptyList();
        }
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        // 处理权限的组合，情况
        for (String auth : auths) {
            if (auth.contains(",")) {
                String[] realAuths = auth.split(",");
                for (String realAuth : realAuths) {
                    grantedAuthorities.add(new SimpleGrantedAuthority(realAuth));
                }
            } else {
                grantedAuthorities.add(new SimpleGrantedAuthority(auth));
            }
        }
        return grantedAuthorities;
    }

    /**
     * 用户的身份 id
     * 店铺id 用户id
     * 组成一个唯一的标识
     *
     * @return
     */
    public String getUsername() {
        return this.userId + "-" + this.shopId;
    }

    public String getPassword() {
        return this.password;
    }

    @Override
    public boolean isAccountNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.status == 1;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isEnabled() {
        return this.status == 1;
    }
}